package com.mulanweb.api.module.controller;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.RandomStringGenerator;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.db.common.WxParaFormatter;
import com.mulanweb.handler.CouponHandler;
import com.mulanweb.handler.wechat.SentModelMessageHandler;
import com.mulanweb.handler.wechat.UserHandler;
import com.mulanweb.utils.AseUtils;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.utils.RandomUtil;
import com.mulanweb.utils.WxSignUtil;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2016/8/26.
 */
@ValidateFile
public class VisaOrderController extends BaseController {

    @ValidateForm
    public void checkPayStatus() throws IOException {
        String orderNumber = getPara("orderNumber");
        String appid = Constant.WeChatFinalValue.APPID;//微信分配的公众账号ID（企业号corpid即为此appId）
        String mch_id = Constant.WeChatFinalValue.MCHID;//微信支付分配的商户号
        String nonce_str = RandomStringGenerator.getRandomStringByLength(32);//这是随机字符串
        String sign = null;
        SortedMap<Object, Object> para = new TreeMap<Object, Object>();
        para.put("appid", appid);
        para.put("mch_id", mch_id);
        para.put("nonce_str", nonce_str);
        para.put("out_trade_no", orderNumber);
        sign = WxSignUtil.createGetPrepayIdSign(para);//进行微信特定签名
        para.put("sign", sign);
        String xml = WxParaFormatter.getRequestXml(para);//将所有参数转换成xml格式

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(Constant.WeChatFinalValue.QUERY_ORDER_URL);
        post.addHeader("Content/Type", "application/xml");
        StringEntity stringEntity = new StringEntity(xml, ContentType.create("application/xml", "UTF-8"));
        post.setEntity(stringEntity);
        CloseableHttpResponse resp = null;
        try {
            resp = client.execute(post);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int returnCode = resp.getStatusLine().getStatusCode();
        String str = "";
        if (200 <= returnCode && 300 >= returnCode) {
            try {
                str = (EntityUtils.toString(resp.getEntity()));

                Map<String, String> result = WxParaFormatter.xmlToMap(str);
                VisaOrder order = VisaOrder.dao.findFirst("SELECT * FROM `visa_order` WHERE order_number = ?", orderNumber);
                if (result.containsKey("trade_state") && "SUCCESS".equals(result.get("trade_state"))) {
                    order.setStatusId(4L);//4,订单已支付状态
                    order.setPayTime(new Date());
                    User user = User.dao.findById(order.getUserId());
                    SentModelMessageHandler.SentVisaOrderSuccessPayModel(orderNumber,user.getOpenId());
                    if (order.update()) {
                        returnJson(1, "操作成功");
                    } else {
                        returnJson(0, "更新失败，系统错误");
                    }
                } else {
                    //订单未支付已过期，优惠券恢复使用次数
                    returnJson(0, "更新失败，未完成支付");
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
        }
    }

    @ValidateForm
    public synchronized void cancelOrder() {

        String openId = getSessionAttr("openId"); // "oULNBwOvt_D2A_8se1bQOQ06ky0w";//

        List<Order> list = Order.dao.find("SELECT *  FROM `order` WHERE DATE_FORMAT(create_time,'%Y-%m-%d') = ? AND user_id=?", DateUtil.dataToYyyyMmDd(new Date()), User.dao.findFirst("SELECT * FROM `user` WHERE open_id=?", openId).getId());
        if (list.size() > 5) {
            returnJson(0, "每日只能取消5次订单,剩余次数为0");
            return;
        }
        if (openId != null && UserHandler.userNotNull(openId)) {
            String orderNumber = getPara("orderNumber");
            Order order = Order.dao.findFirst("SELECT * FROM `order` WHERE order_number=?", orderNumber);
            if (order != null) {
                order.setStatusId(6L);//6 = 订单已过期
                order.update();
                if (order.getTypeId() == 23) {
                    Ticket ticket = Ticket.dao.findById(order.getTargetId());
                    if (ticket != null) {
                        ticket.setSurplusTotal(ticket.getSurplusTotal() + order.getAmount());
                        ticket.update();
                    }
                    //回复优惠券使用次数
                    CouponHandler.cancelCoupon(order.getId());
                }
                returnJson(1, "每日只能取消5次订单,剩余次数为" + (5 - list.size()));
            } else {
                returnFailureJson();
            }
        }
    }
}